package com.hjh.testdemo.ui.camera.record

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.pm.PackageManager
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.MediaStoreOutputOptions
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoRecordEvent
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.navigation.fragment.findNavController
import com.hjh.testdemo.databinding.FragmentCameraRecordBinding
import com.hjh.core.activity.BaseFragment
import com.hjh.testdemo.framework.audio.AudioPlayer
import com.hjq.toast.Toaster
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * @author： hjh
 * @createDate： 2025/6/4 17:03
 * @description： 测试自带摄像头
 * @qq： 3472903821
 * @version: 1.0
 */
class CameraRecordFragment : BaseFragment<FragmentCameraRecordBinding>() {

    private lateinit var preview: Preview
    private lateinit var videoCapture: VideoCapture<Recorder>
    private var recording: Recording? = null
    private var savedVideoUri: Uri? = null

    // 音频播放器
    private lateinit var audioPlayer: AudioPlayer
    private var isAudioPlaying = false

    override fun initView() {
        // 初始化音频播放器
        audioPlayer = AudioPlayer(requireContext())

        requestPermission(
            camera = true,
            audio = true,
            onGranted = {
                startCamera()
            },
            onDenied = {
                findNavController().navigateUp()
            })

        // 设置音频播放按钮
        binding.btnPlayAudio.setOnClickListener {
            if (isAudioPlaying) {
                pauseAudio()
            } else {
                playDefaultAudio()
            }
        }
    }

    private fun playDefaultAudio() {
        // 使用系统默认通知音作为示例音频
        val defaultNotificationUri =
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        audioPlayer.loadAudio(
            uri = defaultNotificationUri,
            onPrepared = {
                audioPlayer.play(
                    onStart = {
                        isAudioPlaying = true
                        binding.btnPlayAudio.text = "暂停音频"
                        Toaster.show("音频开始播放")
                    },
                    onError = { error ->
                        Toaster.show(error)
                    }
                )
            },
            onError = { error ->
                Toaster.show(error)
            }
        )
    }

    private fun pauseAudio() {
        audioPlayer.pause()
        isAudioPlaying = false
        binding.btnPlayAudio.text = "播放音频"
        Toaster.show("音频已暂停")
    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()

            // 预览
            preview = Preview.Builder().build()
            preview.surfaceProvider = binding.previewView.surfaceProvider

            // 视频录制
            val recorder = Recorder.Builder()
                .setQualitySelector(QualitySelector.from(Quality.HIGHEST))
                .build()
            videoCapture = VideoCapture.withOutput(recorder)

            // 绑定到生命周期
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(
                this,
                CameraSelector.DEFAULT_BACK_CAMERA,
                preview,
                videoCapture
            )

            // 开始/停止录制按钮
            binding.btnRecord.setOnClickListener {
                if (recording == null) {
                    startRecording()
                } else {
                    stopRecording()
                }
            }
        }, ContextCompat.getMainExecutor(requireContext()))
    }

    @SuppressLint("ObsoleteSdkInt")
    private fun startRecording() {
        val contentValues = ContentValues().apply {
            val timestamp = SimpleDateFormat(
                "yyyyMMdd_HHmmss",
                Locale.getDefault()
            ).format(Date())
            put(MediaStore.Video.Media.DISPLAY_NAME, "VIDEO_$timestamp.mp4")
            put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/CameraX-Video")
            }
        }

        val mediaStoreOutput = MediaStoreOutputOptions.Builder(
            requireContext().contentResolver,
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        ).setContentValues(contentValues).build()

        if (ActivityCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Toaster.show("无录像权限")
            return
        }
        recording = videoCapture.output
            .prepareRecording(requireContext(), mediaStoreOutput)
            .withAudioEnabled()
            .start(ContextCompat.getMainExecutor(requireContext())) { event ->
                when (event) {
                    is VideoRecordEvent.Start -> {
                        binding.btnRecord.text = "停止录制"
                        Toaster.show("开始录制")
                    }

                    is VideoRecordEvent.Finalize -> {
                        if (event.hasError()) {
                            Toaster.show("录制失败")
                        } else {
                            savedVideoUri = event.outputResults.outputUri
                            Toaster.show("视频已保存")
                            navigateToPlayer(savedVideoUri)
                        }
                        recording = null
                        binding.btnRecord.text = "开始录制"
                    }
                }
            }
    }

    private fun stopRecording() {
        recording?.stop()
    }

    private fun navigateToPlayer(videoUri: Uri?) {
        videoUri?.let {
            // 这里可以跳转到视频播放页面
        }
    }

    override fun onPause() {
        super.onPause()
        // 暂停音频播放
        if (isAudioPlaying) {
            pauseAudio()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放音频播放器资源
        audioPlayer.release()
    }
}